package dnl.util.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.JList;
import javax.swing.ListModel;

public class DList extends JList {

	private ActionListener actionListener;

	public DList() {
		super();
		init();
	}

	public DList(ListModel dataModel) {
		super(dataModel);
		init();
	}

	public DList(Object[] listData) {
		super(listData);
		init();
	}

	public DList(Vector<?> listData) {
		super(listData);
		init();
	}

	private void init() {
		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent me) {
				if (actionListener == null)
					return;
				Object ob[] = getSelectedValues();
				if (ob.length > 1)
					return;
				if (me.getClickCount() == 2) {
					actionListener.actionPerformed(new ActionEvent(this,
							ActionEvent.ACTION_PERFORMED, ob[0].toString()));
					me.consume();
				}
			}
		});

		addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent ke) {
				if (actionListener == null)
					return;
				Object ob[] = getSelectedValues();
				if (ob.length > 1)
					return;
				if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
					actionListener.actionPerformed(new ActionEvent(this,
							ActionEvent.ACTION_PERFORMED, ob[0].toString()));
					ke.consume();
				}
			}
		});
		this.setSelectedIndex(0);
	}

	public void addActionListener(ActionListener al) {
		this.actionListener = al;
	}
}
